import React, { Component } from 'react'
import { Route, Redirect } from 'react-router-dom'
import { authContext } from './authContext'

export default class PrivateRoute extends Component {
  static contextType = authContext

  render() {
    let {children, ...rest} = this.props
    let { user } = this.context
    return (
      <Route
        {...rest}
        render={({ location }) =>
          user ? (
            children
          ) : (
            <Redirect
              to={{
                pathname: "/login",
                state: { from: location }
              }}
            />
          )
        }
      />
    )
  }
}
